package com.basin.common.mongo.handler;

import cn.dev33.satoken.stp.StpUtil;
import com.anwen.mongo.handlers.MetaObjectHandler;
import com.anwen.mongo.model.AutoFillMetaObject;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Component
public class MongoMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(AutoFillMetaObject autoFillMetaObject) {
        Timestamp curTime = getCurTime();
        autoFillMetaObject.fillValue("createTime", curTime);
        autoFillMetaObject.fillValue("updateTime", curTime);
        autoFillMetaObject.fillValue("createUser", getLoginId());
        autoFillMetaObject.fillValue("updateUser", getLoginId());
    }

    @Override
    public void updateFill(AutoFillMetaObject autoFillMetaObject) {
        autoFillMetaObject.fillValue("updateTime", getCurTime());
        autoFillMetaObject.fillValue("updateUser", getLoginId());
    }

    private String getLoginId() {
        return StpUtil.getLoginId("");
    }

    private Timestamp getCurTime() {
        // mongo需要加8小时
        LocalDateTime localDateTime = LocalDateTime.now(ZoneOffset.ofHours(8));
        return Timestamp.from(localDateTime.atZone(ZoneOffset.UTC).toInstant());
    }
}
